import requests
import re
from selenium import webdriver
from time import sleep
from selenium.webdriver import ChromeOptions


class GitHubLogin(object):
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/75.0.3770.100 Safari/537.36',
            'Host': 'github.com',
            'Referer': 'https://github.com/login'
        }
        self.login_url = "https://github.com/login"  # 未登录url
        self.post_url = "https://github.com/session"  # 登录url
        self.session = requests.Session()  # 会话
        self.session.proxies = {'http': 'http://127.0.0.1:10809',
                                'https': 'http://127.0.0.1:10809'}  # TODO: remove proxies

    # 定义一个函数来获取authenticity_token这个参数的值
    def get_authenticity_token(self):
        response = self.session.get(self.login_url, headers=self.headers).text
        pattern_obj = re.compile(r'authenticity_token.*?value="(.*?)" />', re.S)
        authenticity_token = re.search(pattern_obj, response)[1]
        return authenticity_token

    # 拿到authenticity_token这个参数就可以进行模拟登陆了
    def login(self, login, password):
        post_data = {
            'commit': 'Sign in',
            'utf8': '✓',
            'authenticity_token': self.get_authenticity_token(),
            'login': login,
            'password': password
        }
        self.session.post(self.post_url, data=post_data, headers=self.headers)
        print("Logged in")


gh = GitHubLogin()
# gh.login(os.environ['A'], os.environ['B'])
chopt = ChromeOptions()
chopt.add_argument("--proxy-server=http://127.0.0.1:10809") # TODO: remove this!
ch = webdriver.Chrome(executable_path=r"D:\\Application\\chromedriver.exe", options=chopt)
try:
    print(gh.session.cookies)
    ch.get("https://github.com")
    ch.delete_all_cookies()  # 删除selenium侧的所有cookies
    for k,v in gh.session.cookies.items(): #获取requests侧的cookies
        ch.add_cookie({'name':k,'value':v})    #向selenium侧传入以requests侧cookies的name为键value为值的字典

    print("Replacing completed")
    ch.get("https://gitee.com/auth/github")
    sleep(10)
    if ch.title == "我的工作台 - Gitee.com":
        print("Successfully logged into gitee")
    else:
        print(ch.current_url)
        raise Exception("Failed to login")

    for n in ["bukkit", "craftbukkit", "spigot", "builddata"]:
        print("Updating", n)
        ch.get(f"https://gitee.com/SNWCreations/{n}")
        ch.find_element_by_xpath('//*[@id="btn-sync-from-github"]').click()
        sleep(8)
        ch.find_element_by_xpath('/html/body/div[4]/div[3]/div[3]/div[3]').click()
        sleep(10)
        print("Updated", n)
finally:
    ch.quit()
